package com.tommy.test

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class AppItemAdapter : RecyclerView.Adapter<AppItemViewHolder>() {
    private val appItems = arrayListOf<AppItemBean>()
    var itemClickListener: ((position: Int, appItemBean: AppItemBean) -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppItemViewHolder {
        val itemView =
            LayoutInflater.from(parent.context).inflate(R.layout.item_app_view, parent, false)
        return AppItemViewHolder(itemView)
    }

    override fun getItemCount(): Int {
        return appItems.size
    }

    fun setNewItems(newAppItems: List<AppItemBean>) {
        appItems.clear()
        appItems.addAll(newAppItems)
        notifyDataSetChanged()
    }

    override fun onBindViewHolder(holder: AppItemViewHolder, position: Int) {
        val appItemBean = appItems[position]
        holder.tvName?.text = appItemBean.appName
        holder.tvVersionName?.text = appItemBean.appVerName
        holder.tvPackageName?.text = appItemBean.appPackageName
        holder.itemView.setOnClickListener {
            itemClickListener?.invoke(position, appItemBean)
        }
    }
}

class AppItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    var tvName: TextView? = null
    var tvVersionName: TextView? = null
    var tvPackageName: TextView? = null

    init {
        tvName = itemView.findViewById(R.id.tv_name)
        tvVersionName = itemView.findViewById(R.id.tv_version_name)
        tvPackageName = itemView.findViewById(R.id.tv_package_name)
    }
}